/**
 * 最终版枚举分析工具
 * - 手动指定层级关系
 * - 简化控制台输出
 * - 简洁的报告界面
 */

const fs = require('fs');
const Papa = require('papaparse');
const path = require('path');

// 读取配置
function loadConfig() {
    try {
        const configData = fs.readFileSync('枚举分析配置.json', 'utf-8');
        return JSON.parse(configData);
    } catch (e) {
        console.error('❌ 配置文件读取失败');
        process.exit(1);
    }
}

// 判断是否为唯一性字段
function isUniqueField(columnName, uniqueCount, totalCount, config) {
    const lowerName = columnName.toLowerCase();
    const idKeywords = config.字段识别.ID关键词;
    const nameMatch = idKeywords.some(keyword => lowerName.includes(keyword));
    const uniqueRatio = uniqueCount / totalCount;
    const ratioMatch = uniqueRatio > config.字段识别.唯一性阈值;
    return nameMatch || ratioMatch;
}

// 收集字段统计
function collectStats(filePath, config) {
    return new Promise((resolve, reject) => {
        const testMode = config.分析范围.测试模式;
        const maxRows = testMode ? config.分析范围.测试行数 : Infinity;
        
        const fieldStats = {};
        let totalRows = 0;
        let columns = [];
        
        const stream = fs.createReadStream(filePath, { encoding: 'utf-8' });

        Papa.parse(stream, {
            header: true,
            skipEmptyLines: true,
            
            step: function(result, parser) {
                totalRows++;

                if (totalRows === 1 && result.meta.fields) {
                    columns = result.meta.fields;
                    columns.forEach(col => {
                        fieldStats[col] = {
                            values: new Map(),
                            total: 0
                        };
                    });
                }

                columns.forEach(col => {
                    const value = result.data[col];
                    if (!fieldStats[col]) return;
                    
                    fieldStats[col].total++;
                    // 只记录有效值
                    if (value && value !== '数据不存在' && value !== '') {
                        // 限制Map大小，防止内存溢出
                        if (fieldStats[col].values.size < 10000) {
                            const count = fieldStats[col].values.get(value) || 0;
                            fieldStats[col].values.set(value, count + 1);
                        }
                    }
                });

                if (totalRows >= maxRows) {
                    parser.abort();
                }
            },

            complete: function() {
                // 转换统计数据
                Object.keys(fieldStats).forEach(col => {
                    fieldStats[col].uniqueCount = fieldStats[col].values.size;
                    fieldStats[col].uniqueRatio = fieldStats[col].uniqueCount / totalRows;
                    // 转为数组并排序
                    fieldStats[col].valuesList = Array.from(fieldStats[col].values.entries())
                        .sort((a, b) => b[1] - a[1]);
                    // 清理Map释放内存
                    fieldStats[col].values.clear();
                    delete fieldStats[col].values;
                });
                
                resolve({ totalRows, columns, fieldStats });
            },

            error: reject
        });
    });
}

// 分析指定的字段关系
function analyzeSpecificRelation(filePath, parentField, childField, maxRows) {
    return new Promise((resolve) => {
        const relationMap = new Map();
        let rowCount = 0;
        
        const stream = fs.createReadStream(filePath, { encoding: 'utf-8' });
        
        Papa.parse(stream, {
            header: true,
            skipEmptyLines: true,
            step: function(result, parser) {
                rowCount++;
                
                const parentValue = result.data[parentField];
                const childValue = result.data[childField];
                
                if (parentValue && childValue && 
                    parentValue !== '数据不存在' && 
                    childValue !== '数据不存在') {
                    
                    if (!relationMap.has(parentValue)) {
                        relationMap.set(parentValue, new Set());
                    }
                    relationMap.get(parentValue).add(childValue);
                }
                
                if (rowCount >= maxRows) {
                    parser.abort();
                }
            },
            complete: function() {
                const mappings = {};
                relationMap.forEach((childSet, parentValue) => {
                    mappings[parentValue] = Array.from(childSet).sort();
                });
                
                resolve({
                    parent: parentField,
                    child: childField,
                    mappings
                });
            }
        });
    });
}

// 生成简洁的HTML报告
function generateSimpleReport(stats, relationships, config, sourceFile, outputPath) {
    const { totalRows, columns, fieldStats } = stats;
    
    // 分类字段
    const analyzableFields = [];
    const skippedFields = [];
    
    columns.forEach(col => {
        const stat = fieldStats[col];
        if (isUniqueField(col, stat.uniqueCount, stat.total, config)) {
            skippedFields.push(col);
        } else {
            analyzableFields.push(col);
        }
    });
    
    // 生成关系HTML（放在最后展示）
    let relationHtml = '';
    if (relationships.length > 0) {
        relationHtml += `
            <div class="section-header">
                <h1>🔗 字段层级关系 <span class="field-count">${relationships.length}组关系</span></h1>
            </div>
        `;
        
        relationships.forEach(rel => {
            const sortedMappings = Object.entries(rel.mappings)
                .sort((a, b) => b[1].length - a[1].length);
            
            relationHtml += `
                <div class="section">
                    <h2>
                        <span class="field-name-badge">${rel.parent}</span>
                        <span class="arrow">→</span>
                        <span class="field-name-badge">${rel.child}</span>
                        <span class="enum-count">${Object.keys(rel.mappings).length}个父值</span>
                    </h2>
                    <div class="relation-grid">
                        ${sortedMappings.map(([parent, children]) => `
                            <div class="relation-card">
                                <div class="parent-name">${parent} <span class="count">${children.length}</span></div>
                                <div class="child-tags">
                                    ${children.map(c => `<span class="tag">${c}</span>`).join('')}
                                </div>
                            </div>
                        `).join('')}
                    </div>
                </div>
            `;
        });
    }
    
    // 生成字段枚举HTML - 简洁标签形式（先展示枚举）
    let fieldHtml = '';
    
    // 标题：枚举字段统计
    if (analyzableFields.length > 0) {
        fieldHtml += `
            <div class="section-header">
                <h1>📋 字段枚举统计 <span class="field-count">${analyzableFields.length}个字段</span></h1>
            </div>
        `;
    }
    
    analyzableFields.forEach(col => {
        const stat = fieldStats[col];
        const maxDisplay = 200; // 增加显示数量
        
        fieldHtml += `
            <div class="section">
                <h2>
                    <span class="field-name-badge">${col}</span>
                    <span class="enum-count">${stat.uniqueCount}种枚举值</span>
                </h2>
                <div class="enum-tags">
                    ${stat.valuesList.slice(0, maxDisplay).map(([value]) => 
                        `<span class="enum-tag">${value}</span>`
                    ).join('\n                    ')}
                    ${stat.valuesList.length > maxDisplay ? 
                        `\n                    <span class="more-tag">... 还有 ${stat.valuesList.length - maxDisplay} 个</span>` 
                        : ''}
                </div>
            </div>
        `;
    });
    
    const fileName = path.basename(sourceFile, '.csv');
    
    const html = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${fileName} - 枚举分析报告</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            background: #f5f7fa;
            padding: 30px;
            line-height: 1.6;
        }
        .container {
            max-width: 1400px;
            margin: 0 auto;
        }
        .section-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 30px;
            margin-bottom: 25px;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(102,126,234,0.3);
        }
        .section-header h1 {
            font-size: 1.5em;
            font-weight: 600;
            margin: 0;
        }
        .field-count {
            float: right;
            font-size: 0.85em;
            opacity: 0.9;
            font-weight: normal;
        }
        .section {
            background: white;
            margin-bottom: 25px;
            padding: 25px;
            border-radius: 6px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.08);
            border-left: 4px solid #3498db;
        }
        h2 {
            color: #2c3e50;
            font-size: 1.2em;
            margin-bottom: 20px;
            padding-bottom: 12px;
            border-bottom: 2px solid #e8ecf1;
        }
        .field-name-badge {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 0.9em;
            font-weight: 500;
            font-family: 'Consolas', 'Monaco', monospace;
            display: inline-block;
            margin-right: 10px;
            box-shadow: 0 2px 4px rgba(102,126,234,0.3);
        }
        .arrow {
            margin: 0 8px;
            color: #3498db;
            font-weight: bold;
            font-size: 1.1em;
        }
        .enum-count {
            float: right;
            color: #3498db;
            font-size: 0.85em;
            font-weight: normal;
            background: #e8f4f8;
            padding: 4px 12px;
            border-radius: 12px;
        }
        .enum-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            line-height: 1.8;
        }
        .enum-tag {
            background: #ecf0f1;
            padding: 6px 12px;
            border-radius: 4px;
            font-size: 0.9em;
            color: #2c3e50;
            display: inline-block;
        }
        .more-tag {
            color: #7f8c8d;
            font-style: italic;
            padding: 6px 12px;
        }
        .relation-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 15px;
        }
        .relation-card {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 12px;
            background: #fafafa;
        }
        .parent-name {
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 10px;
            padding-bottom: 8px;
            border-bottom: 2px solid #3498db;
        }
        .count {
            float: right;
            background: #3498db;
            color: white;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 0.85em;
        }
        .child-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
        }
        .tag {
            background: #ecf0f1;
            padding: 4px 10px;
            border-radius: 3px;
            font-size: 0.9em;
            color: #2c3e50;
        }
    </style>
</head>
<body>
    <div class="container">
        ${fieldHtml}
        ${relationHtml}
    </div>
</body>
</html>`;

    fs.writeFileSync(outputPath, html, 'utf-8');
}

// 主函数
async function main() {
    const config = loadConfig();
    const filesToAnalyze = config.文件选择.分析所有文件
        ? fs.readdirSync(config.输出设置.输出目录)
            .filter(f => f.endsWith('.csv'))
            .map(f => path.join(config.输出设置.输出目录, f))
        : config.文件选择.指定文件;
    
    if (filesToAnalyze.length === 0) {
        console.log('❌ 未找到要分析的文件');
        return;
    }
    
    console.log(`开始分析 ${filesToAnalyze.length} 个文件...\n`);
    
    for (const filePath of filesToAnalyze) {
        const fileName = path.basename(filePath, '.csv');
        
        try {
            // 收集统计
            const stats = await collectStats(filePath, config);
            
            // 分析关系（如果指定）
            const relationships = [];
            const relationConfigs = config.关系分析.手动指定关系 || [];
            
            if (relationConfigs.length > 0) {
                const maxRows = config.分析范围.测试模式 
                    ? config.分析范围.测试行数 
                    : Infinity;
                
                for (const relConfig of relationConfigs) {
                    const rel = await analyzeSpecificRelation(
                        filePath,
                        relConfig.父字段,
                        relConfig.子字段,
                        maxRows
                    );
                    relationships.push(rel);
                }
            }
            
            // 生成报告
            const outputFileName = config.输出设置.报告文件名格式.replace('{文件名}', fileName);
            const outputPath = path.join(config.输出设置.输出目录, outputFileName);
            
            generateSimpleReport(stats, relationships, config, filePath, outputPath);
            
            console.log(`✅ ${fileName}.csv -> ${outputFileName}`);
            
        } catch (error) {
            console.log(`❌ ${fileName}.csv 分析失败: ${error.message}`);
        }
    }
    
    console.log('\n分析完成！');
}

main();

